package com.geekbang.rpcfx.client.call;

import com.alibaba.fastjson.JSON;
import com.geekbang.rpcfx.api.RpcfxRequest;
import com.geekbang.rpcfx.api.RpcfxResponse;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author nhsoft.lul
 */
public class HttpClientCallImpl implements RpcCall{

    private final CloseableHttpClient client = HttpClientBuilder.create().build();

    @Override
    public <T> RpcfxResponse post(RpcfxRequest<T> req, String url) throws IOException {
        StringEntity entity = new StringEntity(JSON.toJSONString(req), StandardCharsets.UTF_8);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        httpPost.setEntity(entity);
            CloseableHttpResponse response = client.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            HttpEntity responseEntity = response.getEntity();
            return JSON.parseObject(EntityUtils.toString(responseEntity), RpcfxResponse.class);
    }
}
